<%--
  Created by IntelliJ IDEA.
  User: ldh
  Date: 2024/10/16
  Time: 10:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <%--vue--%>
    <script src="/js/vue.js"></script>
    <%--axios--%>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <%--elementui--%>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入组件库 必须在引入vue文件后 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>

    <style>
        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }
        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }
    </style>
</head>
<body>
<div id="app">
    <el-button size="medium" type="success" @click="addUser">添加<i class="el-icon-circle-plus el-icon--right"></i></el-button>
    <%--添加对话框
           el-dialog:对话框标签
              title:标题
              :visible.sync:绑定显示隐藏的属性
    --%>
    <el-dialog title="添加学生" :visible.sync="dialogFormVisible" width="40%">
        <%--
            el-form:表示el的表单元素
               :model 绑定表单数据对象
               lable-width: 表单标签的宽度
        --%>
        <el-form :model="form" label-width="80px" :rules="rules" ref="addForm">
            <el-form-item label="头像:" >
                <%--
                    el-upload: 表单上传组件
                      action: 上传地址
                      show-file-list: 是否显示文件列表
                      on-success: 上传成功回调
                      before-upload: 上传前回调
                --%>
                <el-upload
                        class="avatar-uploader"
                        action="/upload"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item label="姓名:" prop="name">
                <el-input v-model="form.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="年龄:" prop="age">
                <el-input v-model.number="form.age" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="性别">
                <el-radio-group v-model="form.gender">
                    <el-radio label="男" value="男"></el-radio>
                    <el-radio label="女" value="女"></el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="出生日期:">
                <el-date-picker
                        v-model="form.birthday"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择日期时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="班级id:" >
                <el-select v-model="form.classId" placeholder="请选择班级">
                    <el-option v-for="c in clazzList" :label="c.name" :value="c.id"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmAdd">确 定</el-button>
        </div>
    </el-dialog>


    <%--修改的对话框--%>
    <el-dialog title="修改学生" :visible.sync="editDialogFormVisible" width="40%">
        <%--
            el-form:表示el的表单元素
               :model 绑定表单数据对象
               lable-width: 表单标签的宽度
        --%>
        <el-form :model="editForm" label-width="80px" :rules="rules" ref="editForm">
            <el-form-item label="头像:" >
                <%--
                    el-upload: 表单上传组件
                      action: 上传地址
                      show-file-list: 是否显示文件列表
                      on-success: 上传成功回调
                      before-upload: 上传前回调
                --%>
                <el-upload
                        class="avatar-uploader"
                        action="/upload"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                    <img v-if="editForm.headimg" :src="editForm.headimg" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item label="姓名:" prop="name">
                <el-input v-model="editForm.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="年龄:" prop="age">
                <el-input v-model.number="editForm.age" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="性别">
                <el-radio-group v-model="editForm.gender">
                    <el-radio label="男" value="男"></el-radio>
                    <el-radio label="女" value="女"></el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="出生日期:">
                <el-date-picker
                        v-model="editForm.birthday"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择日期时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="班级id:" >
                <el-select v-model="editForm.classId" placeholder="请选择班级">
                    <el-option v-for="c in clazzList" :label="c.name" :value="c.id"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="editDialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmEdit">确 定</el-button>
        </div>
    </el-dialog>
    <%--
        el-table:表示elementui的表格组件
           :data  绑定了vue的数据
           border: 边框
           style:  100%
    --%>

    <el-table
            :data="students"
            border
            style="width: 100%">
        <%--
           el-table-column: 表格列的标签
               prop: 绑定的数据的属性
               label: 列标题
               width: 列的宽度
        --%>
        <el-table-column
                prop="id"
                label="编号"
        >
        </el-table-column>
        <el-table-column
                prop="headimg"
                label="头像"
        >
            <template slot-scope="scope">
                <img :src="scope.row.headimg" width="80"/>
            </template>
        </el-table-column>
        <el-table-column
                prop="name"
                label="姓名"
                width="180">
        </el-table-column>
        <el-table-column
                prop="age"
                label="年龄">
        </el-table-column>
        <el-table-column
                prop="gender"
                label="性别">
        </el-table-column>
        <el-table-column
                prop="birthday"
                label="初始日期">
        </el-table-column>
        <el-table-column
                prop="classInfo.name"
                label="班级">
        </el-table-column>
        <%--fixed:固定右边--%>
        <el-table-column
                label="操作"
                width="220"
        >
            <template slot-scope="scope">

                <el-button size="medium" type="success" @click="edit(scope.row.id)">编辑<i class="el-icon-setting el-icon--right"></i></el-button>
                <el-button size="medium" type="danger" icon="el-icon-delete" @click="del(scope.row.id)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <%--分页组件el-pagination
             @size-change: 每页数据条数改变时会触发
             @current-change: 页码改变时会触发
             current-page: 当前页码
             page-sizes: 每页的数据个数选择器的选项设置
             page-size: 每页的数据条数
             layout: 分页布局
             total: 数据总数
    --%>
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[2, 3, 5, 10]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
    </el-pagination>
</div>
</body>
<script>
    var checkAge = (rule, value, callback) => {
        if (!value) {
            return callback(new Error('年龄不能为空'));
        }
        setTimeout(() => {
            if (!Number.isInteger(value)) {
                callback(new Error('请输入数字值'));
            } else {
                if (value < 18) {
                    callback(new Error('必须年满18岁'));
                } else {
                    callback();
                }
            }
        }, 200);
    };
    let app = new Vue({
        el: "#app",
        data: {
            students: undefined, //无法确定类型时，用undefined
            dialogFormVisible: false,//控制显示和隐藏添加对话框
            editDialogFormVisible: false,//控制显示和隐藏编辑对话框
            form: {}, //表示添加表单对象数据
            editForm:{},//表示编辑表单对象数据
            imageUrl: '', //表示文件上传成功后的路径。
            clazzList:[],//班级列表数据
            rules:{//校验规则
                name: [
                    /*required:必须的 message:错误消息提示 trigger:失焦时触发 */
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                    { min: 2, max: 4, message: '姓名的长度在 2 到 4 个字符', trigger: 'blur' }
                ],
                age: [
                    { validator: checkAge, trigger: 'blur' }
                ]
            },
            currentPage:1,//当前页码
            pageSize:2,//每页显示的条数
            total:0//总记录数

        },
        created() {
            this.loadStudent();//创建完毕，就加载学生数据
            this.loadClazz();//创建完毕，就加载班级数据
        },
        methods: {
            //每页数据条数改变
            handleSizeChange(val) {
               this.pageSize=val;//把改变值赋值给pageSize
                this.loadStudent();
            },
            //页码改变
            handleCurrentChange(val) {
               this.currentPage=val;
               this.loadStudent();
            },
            //确认修改
            confirmEdit(){
                this.$refs.editForm.validate(valid=>{
                    if(valid){
                        axios.put("/student/update",this.editForm).then(resp=>{
                            //关闭对话框
                            this.editDialogFormVisible=false;
                            //提示信息
                            this.$message({
                                type:"success",
                                message:resp.data.msg
                            })
                            //刷新数据
                            this.loadStudent();
                        })
                    }
                })
            },

            //编辑按钮事件
            edit(id){
                this.editDialogFormVisible=true;
                axios.get("/student/getById?id="+id).then(resp=>{
                    this.editForm=resp.data.data;
                })
            },

            //加载所有班级信息
            loadClazz(){
                axios.get("/clazz/list").then(resp=>{
                    //将班级数据设置到form中，让下拉框显示班级数据
                    this.clazzList=resp.data.data;
                })
            },

            //上传成功触发的回调函数 res: 服务器返回的数据，file:上传的文件对象
            handleAvatarSuccess(res, file) {
                this.imageUrl=res.data; //将返回的路径设置到imageUrl中
                this.form.headimg=this.imageUrl; //将上传路径设置到表单中
                this.editForm.headimg=this.imageUrl;
            },
            //上传文件之前的函数
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type==='images/png';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG或png 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            //确认添加
            confirmAdd(){
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        axios.post("/student/add",this.form).then(resp=>{
                            if(resp.data.code===200){
                                this.$notify({
                                    title: '成功',
                                    message: resp.data.msg,
                                    type: 'success'
                                });
                                this.dialogFormVisible = false; //关闭添加弹出框
                                this.loadStudent(); //重新加载表格数据
                            }else{
                                this.$notify({
                                    title: '错误',
                                    message: resp.data.msg,
                                    type: 'error'
                                });
                            }
                        })
                    }
                });


            },
            //添加学生按钮事件--全栈。
            addUser(){
               //显示弹出框
                this.dialogFormVisible = true;

            },

            loadStudent() {
                axios.get("/student/list?pageNum="+this.currentPage+"&pageSize="+this.pageSize).then(resp => {
                    if (resp.data.code === 200) {
                        this.students = resp.data.data.list; //pageInfo
                        this.total=resp.data.data.total;
                    }
                })
            },
            // 删除
            del(id) {
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => { //确认时执行代码块
                    axios.delete("/student/delete?id=" + id).then(resp => {
                        if (resp.data.code === 200) {
                            this.$notify({
                                title: '成功',
                                message: resp.data.msg,
                                type: 'success'
                            });
                            this.loadStudent();
                        } else {
                            this.$notify({
                                title: '错误',
                                message: resp.data.msg,
                                type: 'error'
                            });
                        }
                    })
                }).catch(() => {//取消时执行代码块

                });


            }
        }
    })
</script>
</html>
